package com.example.smscontentobserver;

import androidx.appcompat.app.AppCompatActivity;

import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
        SmsObserver smsObserver;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            smsObserver = new SmsObserver(new Handler());
            getContentResolver().registerContentObserver(Uri.parse("content://sms"), true,smsObserver);
        }
        public class SmsObserver extends ContentObserver {
            public SmsObserver(Handler handler) {
                super(handler);
            }

            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                Toast.makeText(MainActivity.this,"短信发生变化", Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        protected void onDestroy() {
            super.onDestroy();
            getContentResolver().unregisterContentObserver(smsObserver);
        }
    }
